//
//  PTStuLSReleaseDetailViewController.m
//  PlanTech
//
//  Created by ruifeng song on 2018/7/12.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "PTStuLSReleaseDetailViewController.h"
#import "PTStuLSReleaseDetailContentCell.h"
#import "PTStuLSReleaseDetailJobInfoCell.h"
#import "PTStuLSReleaseDetailPeopleInfoCell.h"
#import "PTStuLSReleaseDetailGradeCell.h"
#import "PTCoreObject+LifeService.h"
#import "PTCoreManager+LifeService.h"
#import "PTStuLifeServiceReleaseViewController.h"
#import "PTRateView.h"
#import "SINACalendarUtils.h"

@interface PTStuLSReleaseDetailViewController ()<UITableViewDelegate,UITableViewDataSource,PTRateViewDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)LifeServiceListDetailModel * detailModel;
@property(nonatomic,strong)UITableView *releaseDetailTableView;
@property(nonatomic,strong)UIButton * firstButton;
@property(nonatomic,strong)UIButton * secondButton;

@end

@implementation PTStuLSReleaseDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"发布详情";
    
    self.view.backgroundColor = BaseViewBackgroundColor;
    
    [self createView];
    
    [self requestData];
}

-(UITableView *)releaseDetailTableView
{
    if (_releaseDetailTableView == nil) {
        
        _releaseDetailTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight -(Height_TabBar)-TOP_HEIGHT) style:UITableViewStylePlain];
        _releaseDetailTableView.delegate = self;
        _releaseDetailTableView.dataSource = self;
        _releaseDetailTableView.backgroundColor = [UIColor clearColor];
        _releaseDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _releaseDetailTableView;
}

-(void)createView
{
    UIView * bottomView =[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - (Height_TabBar) -TOP_HEIGHT, ScreenWidth, (Height_TabBar))];
    bottomView.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    _firstButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_firstButton setFrame:CGRectMake(ScreenWidth - 76 - 12, 9, 76, 30)];
    _firstButton.backgroundColor = PTColor_349ef7;
    _firstButton.titleLabel.font = PTFONT_12;
    _firstButton.layer.cornerRadius = 15;
    _firstButton.layer.masksToBounds = YES;
    _firstButton.hidden = YES;
    [_firstButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_firstButton addTarget:self action:@selector(onClickFirstButton:) forControlEvents:UIControlEventTouchUpInside];
    //    [_firstButton setTitle:@"完成" forState:UIControlStateNormal];
    [bottomView addSubview:_firstButton];
    
    _secondButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_secondButton setFrame:CGRectMake(ScreenWidth - (76 * 2) -10 - 12, 9, 76, 30)];
    _secondButton.backgroundColor = PTColor_ff3a31;
    _secondButton.titleLabel.font = PTFONT_12;
    _secondButton.layer.cornerRadius = 15;
    _secondButton.layer.masksToBounds = YES;
    _secondButton.hidden = YES;
    [_secondButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_secondButton addTarget:self action:@selector(onClickSecondButton:) forControlEvents:UIControlEventTouchUpInside];
    //    [_secondButton setTitle:@"举报" forState:UIControlStateNormal];
    [bottomView addSubview:_secondButton];
    
    [self.view addSubview:self.releaseDetailTableView];
}

-(void)requestData
{
    SINAUserModel *userModel = [[SINACommonUserHelper share]getUserModel];
    
    WeakSelf;
    [[PTCoreManager shareInstance]performGetLifeServiceListDetailsWithServiceUUID:self.serviceUUID userUUID:userModel.userUid Completion:^(id  _Nullable retObject, NSError * _Nullable retError) {
        
        if (retObject) {
            
            if ([retObject isKindOfClass:[PTMJsonResult class]]) {
                
            }
            else
            {
                weakSelf.detailModel = retObject;
                
                [weakSelf updateStatusButton];
                
                [weakSelf.releaseDetailTableView reloadData];
            }
        }
        else
        {
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            
        }
        
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([self.detailModel.status integerValue]==PTLifeService_NormalStatus || [self.detailModel.status integerValue] ==PTLifeService_CancelReleaseStatus) {
        return 2;   //待接单、已取消，只显示两项
    }
    else if ([self.detailModel.status integerValue] == PTLifeService_TakeOrderUnDoneStatus || [self.detailModel.status integerValue]==PTLifeService_TakeOrderDoneStatus)
    {
        return 3;   //已接单、待完成，只显示三项
    }
    else if ([self.detailModel.status integerValue] == PTLifeService_CommentStatus)
    {
        return 4;
    }
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section ==0) {
        
        static NSString *ContentCellIdentifier = @"ContentCell";
        PTStuLSReleaseDetailContentCell * contentCell = [tableView dequeueReusableCellWithIdentifier:ContentCellIdentifier];
        if (contentCell == nil) {
            
            contentCell = [[PTStuLSReleaseDetailContentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ContentCellIdentifier];
            contentCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [contentCell updateMyReleaseDetailContentCellWith:self.detailModel];
        return contentCell;
    }
    else if (indexPath.section ==1)
    {
        
        static NSString *JobInfoCellIdentifier = @"JobInfoCell";
        PTStuLSReleaseDetailJobInfoCell * jobInfoCell = [tableView dequeueReusableCellWithIdentifier:JobInfoCellIdentifier];
        if (jobInfoCell == nil) {
            
            jobInfoCell = [[PTStuLSReleaseDetailJobInfoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:JobInfoCellIdentifier];
            jobInfoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [jobInfoCell updateMyReleaseJobInfoCell:self.detailModel];
        
        return jobInfoCell;
    }
    else if (indexPath.section ==2)
    {
        static NSString *PeopleInfoCellIdentifier = @"PeopleInfoCell";
        PTStuLSReleaseDetailPeopleInfoCell * peopleInfoCell = [tableView dequeueReusableCellWithIdentifier:PeopleInfoCellIdentifier];
        if (peopleInfoCell == nil) {
            
            peopleInfoCell = [[PTStuLSReleaseDetailPeopleInfoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PeopleInfoCellIdentifier];
            peopleInfoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [peopleInfoCell updateMyReleasePartJobPeopleInfoCellWith:self.detailModel.receiver];
        
        return peopleInfoCell;
    }
    else if (indexPath.section ==3)
    {
        static NSString *GradeCellIdentifier = @"GradeCell";
        PTStuLSReleaseDetailGradeCell * gradeCell = [tableView dequeueReusableCellWithIdentifier:GradeCellIdentifier];
        if (gradeCell == nil) {
            
            gradeCell = [[PTStuLSReleaseDetailGradeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:GradeCellIdentifier];
            gradeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [gradeCell updateServiceGradeCell:self.detailModel.rating];
        return gradeCell;
    }
    else
    {
        return [[UITableViewCell alloc]init];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            NSString *remarkStr = self.detailModel.remark;
            CGFloat remarkHeight = [remarkStr heightForFont:PTFONT_12 width:(ScreenWidth - 40 - 24 - 40)];
            if (remarkHeight ==0) {
                remarkHeight = 15;
            }
            
            NSString * addressStr  = self.detailModel.userAddress;
            CGFloat addressHeight = [addressStr heightForFont:PTFONT_12 width:ScreenWidth - 40 - 24 - 62];
            
            return (remarkHeight + addressHeight + 40 + 100 + 10);
            break;
        }
        case 1:
            return 109;
            break;
        case 2:
            return 80;
            break;
        case 3:
            return 80;
            break;
    }
    return 0;
}

-(void)updateStatusButton
{
    switch ([self.detailModel.status integerValue]) {
        case PTLifeService_NormalStatus:
        {
            //判断是否已经过期
            if ([[SINACalendarUtils currentTimeStr] doubleValue]>[self.detailModel.endTime doubleValue]) {
                
                self.secondButton.hidden = NO;
                self.firstButton.hidden = NO;
                [self.firstButton setTitle:@"重新发布" forState:UIControlStateNormal];
                [self.secondButton setTitle:@"已过期" forState:UIControlStateNormal];
                self.secondButton.tag = MyReleaseOrder_TimeOutType;
                self.firstButton.tag = MyReleaseOrder_ResetType;
                
                self.firstButton.backgroundColor = PTColor_349ef7;
                self.secondButton.backgroundColor = PTColor_ff3a31;
            }
            else
            {
                self.secondButton.hidden = YES;
                self.firstButton.hidden = NO;
                [self.firstButton setTitle:@"取消订单" forState:UIControlStateNormal];
                self.firstButton.tag = MyReleaseOrder_CancelType;
                self.firstButton.backgroundColor = PTColor_349ef7;
            }
            
        }
            break;
        case PTLifeService_CancelReleaseStatus:
        {
            
            self.secondButton.hidden = NO;
            self.firstButton.hidden = NO;
            [self.firstButton setTitle:@"重新发布" forState:UIControlStateNormal];
            [self.secondButton setTitle:@"删除订单" forState:UIControlStateNormal];
            self.secondButton.tag = MyReleaseOrder_DeleteType;
            self.firstButton.tag = MyReleaseOrder_ResetType;
            
            self.firstButton.backgroundColor = PTColor_349ef7;
            
            self.secondButton.backgroundColor = PTColor_ff3a31;
            
        }
            break;
        case PTLifeService_TakeOrderUnDoneStatus:
        {
            self.firstButton.hidden = YES;
            self.secondButton.hidden = YES;
        }
            break;
        case PTLifeService_TakeOrderDoneStatus:
        {
            self.firstButton.hidden = NO;
            self.secondButton.hidden = NO;
            [self.firstButton setTitle:@"完成" forState:UIControlStateNormal];
            [self.secondButton setTitle:@"举报" forState:UIControlStateNormal];
            self.firstButton.tag = MyReleaseOrder_FinishType;
            self.secondButton.tag = MyReleaseOrder_ReprotType;
            self.firstButton.backgroundColor = PTColor_349ef7;
            self.secondButton.backgroundColor = PTColor_ff3a31;
        }
            break;
        case PTLifeService_CommentStatus:
        {
            
            self.secondButton.hidden = YES;
            self.firstButton.hidden = NO;
            [self.firstButton setTitle:@"删除订单" forState:UIControlStateNormal];
            self.firstButton.tag = MyReleaseOrder_DeleteType;
            self.firstButton.backgroundColor = PTColor_ff3a31;
            
        }
            break;
        case PTLifeService_FinishStatus:
        {
            self.secondButton.hidden = YES;
            self.firstButton.hidden = NO;
            [self.firstButton setTitle:@"评价" forState:UIControlStateNormal];
            self.firstButton.tag = MyReleaseOrder_CommentType;
            self.firstButton.backgroundColor = PTColor_349ef7;
        }
            break;
        case PTLifeService_WaitSolveStatus:
        {
            
            self.secondButton.hidden = YES;
            self.firstButton.hidden = NO;
            [self.firstButton setTitle:@"已举报" forState:UIControlStateNormal];
            self.firstButton.tag = MyReleaseOrder_ReportFinishType;
            
            self.firstButton.backgroundColor = PTColor_ff3a31;
        }
            
            break;
    }
}

-(void)onClickFirstButton:(UIButton *)sender
{
    //完成、取消订单、已举报、评价、删除订单、重新发布
    if (sender.tag == MyReleaseOrder_FinishType) {
        
        [self onClickFinishOrderItem];
    }
    else if (sender.tag == MyReleaseOrder_CancelType)
    {
        [self onClickCancelOrderItem];
    }
    else if (sender.tag == MyReleaseOrder_ReportFinishType)
    {
        //只显示，不做任何操作
    }
    else if (sender.tag == MyReleaseOrder_CommentType)
    {
        [self onClickCommentsOrderItem];
    }
    else if (sender.tag == MyReleaseOrder_DeleteType)
    {
        //取消订单后，显示的删除订单按钮
        [self onClickDeleteOrderItem];
    }
    else if (sender.tag == MyReleaseOrder_ResetType)
    {
        [self onClickResetReleaseOrderItem];
    }
}

-(void)onClickSecondButton:(UIButton *)sender
{
    //举报 、删除订单
    if (sender.tag == MyReleaseOrder_ReprotType) {
        
        [self onClickReportUserItem];
    }
    else if (sender.tag == MyReleaseOrder_DeleteType)
    {
        //完成订单，删除
        [self onClickDeleteOrderItem];
    }
    else if (sender.tag == MyReleaseOrder_TimeOutType)
    {
        
    }
}
//取消订单
-(void)onClickCancelOrderItem
{
    UIAlertView * alertView  =[[UIAlertView alloc]initWithTitle:nil message:@"确定取消此订单?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag =11;
    [alertView show];
}

//删除订单
-(void)onClickDeleteOrderItem
{
    UIAlertView * alertView  =[[UIAlertView alloc]initWithTitle:nil message:@"确定删除此订单？\n（删除后不可恢复）" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag = 22;
    [alertView show];
    
}

//重新发布
-(void)onClickResetReleaseOrderItem
{
    PTStuLifeServiceReleaseViewController * lifeServiceReleaseViewController = [[PTStuLifeServiceReleaseViewController alloc]init];
    lifeServiceReleaseViewController.isTimeoutOrder = YES;
    lifeServiceReleaseViewController.listModel = self.detailModel;
    [lifeServiceReleaseViewController setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:lifeServiceReleaseViewController animated:YES];
}

//举报
-(void)onClickReportUserItem
{
    SINAUserModel *userModel = [[SINACommonUserHelper share]getUserModel];
    
    WeakSelf;
    [[PTCoreManager shareInstance]performPostReportUserWithUserName:userModel.userRealName receiverUUID:self.detailModel.receiver.uuid serviceUUID:self.detailModel.serviceUUID type:[self.detailModel.type integerValue] missionUUID:self.detailModel.missionUUID Completion:^(PTMJsonResult * retObject, NSError * _Nullable retError) {
        
        if (retObject) {
            
            if ([retObject.code integerValue] == kPTCore_Response_Code) {
                
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已举报" delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alertView.tag = 2222;
                [alertView show];
                
                [weakSelf requestData];
            }
        }
        else
        {
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            
        }
    }];
}

//评价
-(void)onClickCommentsOrderItem
{
    //显示评价视图
    PTRateView * rateView = [[PTRateView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    rateView.delegate = self;
    [rateView setMyListModel:self.detailModel];
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:rateView];
}

//完成
-(void)onClickFinishOrderItem
{
    UIAlertView * alertView  =[[UIAlertView alloc]initWithTitle:nil message:@"确定对方已完成该任务？\n（完成后不可撤回）" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.tag = 33;
    [alertView show];
}

#pragma mark - PTRateViewDelegate  method
-(void)submitRatingInfo:(PTRateView *)rateView
{
    WeakSelf;
    [[PTCoreManager shareInstance]performPostPublisherEvaluateWithUserName:rateView.myListModel.userName receiverUUID:rateView.myListModel.receiver.uuid serviceUUID:rateView.myListModel.serviceUUID missionUUID:rateView.myListModel.missionUUID type:[rateView.myListModel.type integerValue] rating:rateView.rating Completion:^(PTMJsonResult *retObject, NSError * _Nullable retError) {
        
        [rateView removeFromSuperview];
        
        if (retObject) {
            
            if ([retObject.code integerValue] == kPTCore_Response_Code) {
                
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已评价" delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alertView.tag = 2222;
                [alertView show];
                
                [weakSelf requestData];
            }
        }
        else
        {
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
    }];
}

#pragma mark - UIAlertViewDelegate Method
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 22 && buttonIndex ==1) {
        
        WeakSelf;
        [[PTCoreManager shareInstance]performPostDeleteMyReleaseOrderWithServiceUUID:self.detailModel.serviceUUID Completion:^(PTMJsonResult * retObject, NSError * _Nullable retError) {
            
            if (retObject) {
                
                if ([retObject.code integerValue]  == 1000) {
                    
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已删除" delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    alertView.tag = 1111;
                    [alertView show];
                }
            }
            else
            {
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
        }];
    }
    else if (alertView.tag ==11 && buttonIndex == 1)
    {
        WeakSelf;
        [[PTCoreManager shareInstance]performPostCancelMyReleaseOrderWithServiceUUID:self.detailModel.serviceUUID Completion:^(PTMJsonResult * retObject, NSError * _Nullable retError) {
            
            if (retObject) {
                
                if ([retObject.code integerValue]  == kPTCore_Response_Code) {
                    
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已取消" delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    alertView.tag = 2222;
                    [alertView show];
                    
                     [weakSelf requestData];
                
                }
            }
            else
            {
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            
        }];
    }
    else if (alertView.tag ==33 && buttonIndex ==1)
    {
        WeakSelf;
        [[PTCoreManager shareInstance]performPostConfirmFinishOrderWithUserName:self.detailModel.userName receiverUUID:self.detailModel.receiver.uuid serviceUUID:self.detailModel.serviceUUID type:[self.detailModel.type integerValue] missionUUID:self.detailModel.missionUUID Completion:^(PTMJsonResult * retObject, NSError * _Nullable retError) {
            
            if (retObject) {
                
                if ([retObject.code integerValue] == kPTCore_Response_Code) {
                    
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已完成" delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    alertView.tag = 2222;
                    [alertView show];
                    
                    [weakSelf requestData];
                }
            }
            else
            {
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            
        }];
    }
    else if (alertView.tag ==1111 && buttonIndex == 0)
    {
        //已删除
        [[NSNotificationCenter defaultCenter]postNotificationName:kPT_Global_Notification_RefreshMyReleaseList object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if (alertView.tag ==2222 && buttonIndex ==0)
    {
        //其他状态
        [[NSNotificationCenter defaultCenter]postNotificationName:kPT_Global_Notification_RefreshMyReleaseList object:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
